package com.jldx.oa.controller;

import java.util.Date;
import java.util.List;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jldx.common.NoUtil;
import com.jldx.common.Result;
import com.jldx.oa.bean.BuyOrder;
import com.jldx.oa.bean.Goods;
import com.jldx.oa.bean.Partner;
import com.jldx.oa.bean.User;

public class BuyOrderController extends BaseController{

	public void index(){
		render("/WEB-INF/views/buy_order.html");
	}
	
	public void query(){
		Integer pageNumber = getPage();
		String name = getPara("name");
		Integer limit = getLimit();
		Kv cond = Kv.by("remark", name);
		SqlPara sqlPara = Db.getSqlPara("oa.buyOrderList",cond);
		Page<BuyOrder> page = BuyOrder.dao.paginate(pageNumber, limit, sqlPara);
		Result result = Result.cast(page);
		renderJson(result);
	}
	
	public void edit(){
		Integer id = getParaToInt("id");
		if(id!=null){
			BuyOrder buy_order = BuyOrder.dao.findById(id);
			setAttr("buy_order", buy_order);
		}
		List<Goods> gs = Goods.dao.find("select * from goods ");
		setAttr("gs", gs);
		List<User> ps = User.dao.find("select * from user where type='sup'");
		setAttr("ps",ps);
		view("buy_order_edit.html");
	}
	
	public void save(){
		BuyOrder buy_order = getModel(BuyOrder.class,"");
		if(buy_order.getId()!=null){
			if("done".equals(buy_order.getState())){
				Goods goods = Goods.dao.findById(buy_order.getGoodsId());
				goods.setStoreCount(goods.getStoreCount()+buy_order.getAmount().intValue());
				goods.update();
			}
			buy_order.update();
		}else{
			buy_order.setCreateTime(new Date());
			buy_order.setNo(NoUtil.createNo("buy"));
			buy_order.setUserId(getCurrentUser().getId());
			buy_order.save();
		}
		renderText("suc");
	}
	
	public void delete(){
		Integer id = getParaToInt("id");
		boolean result = false;
		if(id!=null){
			result = BuyOrder.dao.deleteById(id);
		}
		if(result){
			renderText("suc");
		}else{
			render("fail");
		}
	}
}
